#coding=UTF-8
#! /usr/local/bin/python
# -*- coding: UTF-8 -*-
# Filename=backup.py
#coding=UTF-8
'''
Created on 2012-10-23

@author: Du Jianxiong
'''
import os
import time
import ConfigParser
import re
import shutil
import ConfigParser
import commands
from datetime import datetime,date,timedelta
import traceback
import sys
reload(sys) 
sys.setdefaultencoding('utf-8')

def showMessage(str):
        '''打印字符串'''
        print  str.decode('utf-8')
try:
    #python 2.6
    strptime = strptime
except Exception,err:
    #python 2.4 equivalent
    strptime = lambda date_string, format: datetime(*(time.strptime(date_string, format)[0:6]))
    
cf=ConfigParser.ConfigParser()
cf.read("/home/ucun/htdocs/python/down/script/ucpacker/ucpacker.ini")
logdp=cf.get('common','logdp');
scriptDir=cf.get('common','scriptDir');
daydiff = int(cf.get('common','daydiff'))
#时间跨度startday-today
today = date.today();
agoday = today - timedelta(daydiff+7);

try:
        #删除备忘录文件夹
        for fn in os.listdir(logdp):
            if re.match(r"\d{4}-\d{1,2}-\d{1,2}",fn):
                if (strptime(fn,'%Y-%m-%d').date())<=agoday:
                    shutil.rmtree(logdp+"/"+fn)
                    showMessage("deleted "+logdp+"/"+fn)
        #删除status
        sdir = os.path.join(scriptDir,"status")
        if(os.path.exists(sdir)):
            for sn in os.listdir(sdir):
                if re.match(r"\d{4}-\d{1,2}-\d{1,2}",sn):
                    if (strptime(sn,'%Y-%m-%d').date())<=agoday:
                        os.remove(sdir+"/"+sn)
                        showMessage("deleted "+sdir+"/"+sn)
        #删除error
        edir = os.path.join(scriptDir,"error")
        if(os.path.exists(edir)):
            for en in os.listdir(edir):
                if re.match(r"\d{4}-\d{1,2}-\d{1,2}",en):
                    if (strptime(en,'%Y-%m-%d').date())<=agoday:
                        os.remove(edir+"/"+en)
                        showMessage("deleted "+edir+"/"+en)
except Exception,err:  
        print "["+time.strftime('%Y-%m-%d %X')+"]`"+traceback.format_exc()                   
        
